import { forwardRef, useCallback, useEffect, useImperativeHandle } from 'react';
import { Input } from 'antd-mobile';
import { connect, useField, mapProps } from '@formily/react';
import { Field } from '@formily/core';
import { inbiz } from '@inbiz/render';
import { getMessage, TextWidget } from '@inbiz/react';
import { useEvents } from '@inbiz/utils';
import { defaultProps } from '../../designer/schema';
import api from '../web/api';
import './index.less';

export type IProps = {
  value: string;
  readOnly: boolean;
  disabled: boolean;
  inbiz: inbiz;
  title: string;
  addonAfter: string;
  maximum: number;
  minimum: number;
  emit?: () => void;
  callBackEvents?: {
    onBeforeChange?: (v: string) => boolean;
  };
  onChange: (v: any) => void;
  viewMode?:string;
  prefix?:string;
} & typeof defaultProps;

const EformNumberInput = forwardRef((props: IProps, ref: any) => {
  const { value, precision, maximum, minimum, placeholder, viewMode, prefix } = props;
  const filed = useField<Field>();
  const [configEvents] = useEvents(props.callBackEvents, props.emit);

  useImperativeHandle(
    ref,
    () => ({
      ...api(configEvents, props, filed),
    }),
    [],
  );

  useEffect(() => {
    filed.setValidatorRule('validator', (value: string, rule: any, ctx: any) => {
      if (ctx.field.componentProps.maxLength && value) {
        if (value.toString().length > ctx.field.componentProps.maxLength) {
          return (
            <>
              <TextWidget>EformNumber.validate.maxLengthNumber</TextWidget>
              {ctx.field.componentProps.maxLength}
            </>
          );
        }
      }
      if (ctx.field.componentProps.maximum && value) {
        if (maximum && Number(value) > maximum) {
          return (
            <>
              <TextWidget>EformNumber.validate.maximum</TextWidget>
              {maximum}
            </>
          );
        }
      }
      if (ctx.field.componentProps.minimum && value) {
        if (minimum && Number(value) < minimum) {
          // return getMessage('EformNumber.validate.minimum') + minimum;
          return (
            <>
              <TextWidget>EformNumber.validate.minimum</TextWidget>
              {minimum}
            </>
          );
        }
      }
      return true;
    });
  }, []);

  const onChange = useCallback((v) => {
    // 允许输入正负整数、正负小数
    if (/^-$|^-?\d{0,}[.]?$|^-?\d{0,}[.]\d+/.test(v)) {
      props.onChange(v);
    } else if (!v) {
      props.onChange('');
    }
  }, []);

  const onBlur = useCallback(
    (e) => {
      if (value + '' != '') {
        // 控制数字有效性
        let newValue = value || '';
        let v = parseFloat(value + '' || '');
        if (isNaN(v)) {
          newValue = '';
        } else {
          if (v + '' != value + '') {
            newValue = v + '';
          }
        }

        if (newValue != '') {
          // 控制精度
          if (precision && precision >= 0) {
            newValue = parseFloat(newValue + '').toFixed(precision);
          } else if (!precision) {
            newValue = parseFloat(newValue + '').toFixed(0);
          }
        }

        if (newValue != value) {
          // 最终控制数字有效性，保证不出现NaN
          let v1 = parseFloat(newValue + '' || '');
          if (isNaN(v1)) {
            newValue = '';
          }
          props.onChange(newValue);
        }
      }
    },
    [value, precision],
  );

  return viewMode == 'look' ?<div style={{fontSize:'16px'}}>{`${prefix ? prefix : ''}${value?value:''}${props.addonAfter ? props.addonAfter : ''}`}</div>  :<Input {...props} value={(props.value === null || props.value === undefined) ? '' : props.value} onChange={onChange} placeholder={placeholder} onBlur={onBlur} />;
});
(
  EformNumberInput as typeof EformNumberInput & IDefaultValueFormat<typeof defaultProps>
).defaultValueFormat = (props: any): string | void | null => {
  if (props.defaultValue) {
    if (props.precision) {
      const [int, decimal = ''] = props.defaultValue.toString().split('.');
      if (props.precision > decimal.length) {
        const str = '0'.repeat(props.precision - decimal.length);
        return int + '.' + decimal + str;
      } else {
        return props.defaultValue;
      }
    } else {
      return props.defaultValue;
    }
  }
  if (!props.value) {
    return null;
  }
};
export default connect(
  EformNumberInput,
  mapProps({}, (props: any, field: any) => {
    const { addonAfter, prefix, ...others } = props;
    if(props.viewMode!='look'){
      field.decoratorProps.addonAfter = addonAfter;
      field.decoratorProps.addonBefore = prefix;
    }else{
      field.decoratorProps.addonAfter = '';
      field.decoratorProps.addonBefore = '';
    }
    others.placeholder = getMessage(props.placeholder);
    return { ...others };
  }),
);
